﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using Cqrs.Infrastructure;
using Microsoft.Win32;
using System.Reflection;
using Cqrs.StateMachineDesigner.CustomCode;

namespace Cqrs.StateMachineDesigner.Database
{
    /// <summary>
    /// Interaction logic for SaveToDatabase.xaml
    /// </summary>
    public partial class SaveLoadToDatabase : Window
    {
        public SaveLoadToDatabase()
        {
            InitializeComponent();
        }

        private enum EditType
        {
            Loading,
            Saving
        }

        private DataGrid _datagrid;
        private StateMachineRecord _stateMachineRecord;
        private EditType _editType;

        public StateMachineRecord LoadStateMachine()
        {
            this.btnLoad.Margin = this.btnSave.Margin;
            btnSave.Visibility = Visibility.Hidden;
            //grdDetails.Visibility = Visibility.Hidden;
            //Thickness margin = border.Margin;
            //margin.Bottom = 50;
            //border.Margin = margin;
            _editType = EditType.Loading;

            RefreshGrid();
            this.ShowDialog();

            return _stateMachineRecord;
        }

        public StateMachineRecord SaveStateMachine(StateMachineRecord stateMachine)
        {
            btnLoad.Visibility = System.Windows.Visibility.Hidden;
            _stateMachineRecord = stateMachine;
            
            txtName.Text = _stateMachineRecord.Name;
            txtAssemblyType.Text = _stateMachineRecord.AssemblyType;
            txtAssemblyLocation.Text = _stateMachineRecord.AssemblyLocation;

            _editType = EditType.Saving;
            RefreshGrid();
            this.ShowDialog();
            return _stateMachineRecord;
        }

        private void RefreshGrid()
        {
            //LoadSpinner();

            _datagrid = (DataGrid)grdContent.Children[0];
            Spinner.Load(grdContent, "Loading State Machines...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }

        private void LoadSpinner()
        {
            _datagrid = (DataGrid)grdContent.Children[0];
            ContentControl cont = new ContentControl();
            cont.Content = new TextBlock() { Text = "Loading State Machines..." };
            cont.Style = (Style)grdContent.FindResource("LoadingSpinner");
            grdContent.Children.Clear();
            grdContent.Children.Add(cont);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            //e.Result = (IList<StateMachineRecord>)StateMachineRecord.GetAllStateMachines();
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.grdStateMachines.ItemsSource = (IList<StateMachineRecord>)e.Result;
            grdContent.Children.Clear();
            grdContent.Children.Add(_datagrid);
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveMachine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadMachine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void SaveMachine()
        {

            List<StateMachineRecord> stateMachines = (List<StateMachineRecord>)grdStateMachines.ItemsSource;
            if (stateMachines.Exists(p => p.Name == txtName.Text && p.Name != _stateMachineRecord.Name))
            {
                if (MessageBox.Show("This State Machine already exists.  Do you want to overwrite it?", "State Machine", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;
            }

            _stateMachineRecord.Name = txtName.Text;
            _stateMachineRecord.AssemblyType = txtAssemblyType.Text;
            _stateMachineRecord.AssemblyLocation = txtAssemblyLocation.Text;
            if (stateMachines.Exists(p => p.Name == _stateMachineRecord.Name))
            {
                //StateMachineRecord.UpdateStateMachine(_stateMachineRecord);
            }
            else
            {
                //StateMachineRecord.InsertStateMachine(_stateMachineRecord);
            }

            this.Close();

        }

        private void LoadMachine()
        {
            if (grdStateMachines.SelectedItem == null)
                return;

            _stateMachineRecord = (StateMachineRecord)grdStateMachines.SelectedItem;

            this.Close();
        }

        private void grdStateMachines_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (grdStateMachines.SelectedItem == null) return;
                if (_editType == EditType.Loading)
                    LoadMachine();
                else
                    SaveMachine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void grdStateMachines_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ContextMenu mainMenu = new ContextMenu();
                grdStateMachines.ContextMenu = mainMenu;

                MenuItem delete = new MenuItem();
                delete.Header = "Delete";
                delete.Foreground = Brushes.Black;
                delete.Background = Brushes.Transparent;
                mainMenu.Items.Add(delete);
                delete.Click += new RoutedEventHandler(delete_Click);
            }
            catch
            {
            }
        }

        void delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (grdStateMachines.SelectedItem == null)
                    return;
                //StateMachineRecord.DeleteStateMachine(((StateMachineRecord)grdStateMachines.SelectedItem).Name);
                RefreshGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnSelectAssembly_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Filter = "Assembly Files (*.dll)|*.dll|(*.exe)|*.exe|All Files (*.*)|*.*";

                if (openFile.ShowDialog() == true)
                {
                    string fileName = openFile.FileName;
                    Assembly assembly = Assembly.LoadFrom(openFile.FileName);
                    SelectDomainType selectForm = new SelectDomainType();
                    txtAssemblyLocation.Text = assembly.Location;
                    txtAssemblyType.Text = selectForm.select(assembly).AssemblyQualifiedName;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    }
}
